package com.hgcode.platform.rocketmq.producer;

import com.hgcode.platform.config.rocketmq.RocketMqConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class OrderProducer {

    private static final Logger logger = LoggerFactory.getLogger(OrderProducer.class);

    private DefaultMQProducer producer = null;

    @Autowired
    private RocketMqConfig config;

    @PostConstruct
    public void start() {
        try {
            logger.info("MQ：启动MdmDataProducer生产者");
            producer = new DefaultMQProducer(config.getOrderGroup());
            producer.setNamesrvAddr(config.getNamesrvAddr());
            producer.start();
        } catch (MQClientException e) {
            logger.error("MQ：启动MdmDataProducer生产者失败：{}-{}", e);
        }
    }

    @PreDestroy
    public void destory() {
        if (producer != null) {
            producer.shutdown();
            logger.info("MQ：关闭MdmDataProducer生产者");
        }
    }

    /**
     * 功能描述: 发送消息
     * @auther: wentao_tang
     * @date: 2018-12-10 15:13
     */
    public void sendMessage(String message) throws Exception {
        byte[] messageData = message.getBytes(RemotingHelper.DEFAULT_CHARSET);
        Message mqMsg = new Message(config.getOrderTopic(), config.getOrderTag(), System.currentTimeMillis() + "_" + "order", messageData);
        producer.send(mqMsg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("OrderProducer|sendMessage|消息发送成功回调:{}", sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
                logger.error("OrderProducer|sendMessage|消息发送异常回调:{}", throwable);
            }
        });

    }

}
